package club.xcgame520.picturepickerdemo;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class WelcomeActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    private final String[] permissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        checkPermissions();

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            checkPermissions();
        }

    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        for (String perm : perms) {
            Log.d("xiaocan", "已允许权限" + perm);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        if (requestCode == 1) {

            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

                new AppSettingsDialog.Builder(this)
                        .setRationale("使用此应用需要使用读取手机状态权限、读写文件权限、定位权限、相机权限，否则无法正常使用，是否打开应用设置修改应用权限！")
                        .setTitle("温馨提示")
                        .setPositiveButton("去开启")
                        .setNegativeButton("否")
                        .build()
                        .show();
            }

        }

    }


    @AfterPermissionGranted(1)
    private void checkPermissions() {
        if (EasyPermissions.hasPermissions(this, permissions)) {

            Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
            startActivity(intent);
            finish();

        } else {
            EasyPermissions.requestPermissions(this, "使用此应用需要使用读取手机状态权限、读写文件权限、定位权限、相机权限！", 1, permissions);
        }
    }

    private Handler handler = new Handler();

}
